define(["jquery"], function ($) {
    //进行数据请求
    async function responseSend() {
        await $.ajax({
            url: "../data/listgoods.json",
            type: "get",
            dataType: "json",
            success: function (jsonArr) {
                console.log(jsonArr);
                console.log(jsonArr.length);
                // 对获得的json对象数据遍历展现给页面
                $.each(jsonArr, function (index, item) {
                    let goodsDom = `
                        <li>
                        <a class="a-top" target=_blank href="./detail.html?code=${item.code}">
                            <img src="${item.imgurl}" alt="">
                        </a>
                        <p class="massage">
                            <span>￥${item.price}</span>
                            <span>评价${item.evaluate}</span>
                        </p>
                        <p class="tit">
                            <a href="./detail.html?${item.code}">${item.title}
                            </a>
                        </p>
                        <h5>${item.sideTit}
                        </h5>
                        <p class="tag">
                            <span class="merchant">自营</span>
                            <span class="coupon"><em></em><i>${item.discounts}</i><em></em></span>
                        </p>
                        <div class="item_compare">
                            <div class="cart" code=${item.code} >
                                <i></i>
                                <span>加入购物车</span>
                            </div>
                        </div>
                        <p class="tag_wrap">
                            ${item.tag}
                        </p>
                    </li>
                    `;
                    $(".navlist").append(goodsDom);
                });
            }
        });

        addCart();
    }

    function addCart() {
        console.log(111111111);
        console.log($('.navlist'));
        $('.navlist').on('click', '.cart', function () {
            // 如果没有商品则加入商品到购物车里;
            let goodsArr = [];
            if (localStorage.getItem("goods")) {
                goodsArr = JSON.parse(localStorage.getItem("goods"));
            }
            let code = $(this).attr("code");
            // 设置一个标志属性
            let flag = false;
            $.each(goodsArr, function (index, item) {
                if (item.code === code) {
                    item.num++;
                    flag = true;
                    return false;
                }
            });
            // 如果购物车里含有数据则值进行数量加一
            if (!flag) {
                goodsArr.push({
                    code: code,
                    num: 1
                });
            }
            //    数据存储到本地
            localStorage.setItem("goods", JSON.stringify(goodsArr));
            alert("添加成功");
        });
    }

    return {
        responseSend: responseSend,
    }
})